#include <stdio.h>
#include <stdlib.h>
#include "pic.h"
#include "Yeux3.h"

static char table[]="OpenScrapeExampleTM.tm";
static char img_file[]="rectangle.ppm";
#define RGB_COMPONENT_COLOR 255

/* http://stackoverflow.com/questions/2693631/read-ppm-file-and-store-it-in-an-array-coded-with-c */
struct simg *load_img(char *filename)
{
	unsigned char c;
	unsigned char rgb_comp_color;
	char buf[16];
	struct simg *img=NULL;

	FILE *f=fopen(filename, "rb");
	if (!f) goto err;
	
	img = (struct simg *)malloc(sizeof(struct simg));
	if (!img) goto err;
	
	/* check the image format */
	if (!fgets(buf, sizeof(buf), f))
		goto err;
	if (buf[0] != 'P' || buf[1] != '6')
		goto err;

	/* check for comments */
	c = getc(f);
	while(c=='#') {
		while(getc(f) != '\n');
		c=getc(f);
	};
	ungetc(c, f);

	/* read image size information */
	if (fscanf(f, "%d %d", &img->w, &img->h) != 2) {
		fprintf(stderr, "Invalid image size\n");
		goto err; 
	}
	img->b = 3;

	//read rgb component
	if (fscanf(f, "%hhu", &rgb_comp_color) != 1) {
		 fprintf(stderr, "Invalid rgb component (error loading '%s')\n"
			, filename);
		 goto err;
	}

	//check rgb component depth
	if (rgb_comp_color!= RGB_COMPONENT_COLOR) {
		 fprintf(stderr, "'%s' does not have 8-bits components\n"
			, filename);
		 goto err;
	}

	while (fgetc(f) != '\n') ;
	//memory allocation for pixel data
	img->pixels = (uint8_t*)malloc(img->w * img->h * img->b * sizeof(char));

	if (!img) {
		fprintf(stderr, "Unable to allocate memory\n");
		goto err;
	}

	//read pixel data from file
	if (fread(img->pixels, 3 * img->w, img->h, f) != (size_t)img->h) {
		fprintf(stderr, "Error loading image '%s'\n", filename);
		goto err;
	}

	fclose(f);
	return img;

err:
	if (f) fclose(f);
	if (img) {
		if (img->pixels) free(img->pixels);
		free(img);
	}
	return NULL;
}

int main()
{
	struct simg *img;
	char res[128];

	printf("open table %s\n", table);
	if (open_tablemap(table)) {
		fprintf(stderr, "error while opening %s\n", table);
		return -1;
	}

	printf("load img %s\n", img_file);
	img = load_img(img_file);
	if (!img)
		return -1;

	if (read_region(img, "test", res, sizeof(res), 0)) {
		fprintf(stderr, "cannot read a region\n");
		return -1;
	}
	printf("read reagion test=>%s\n", res);
	
	printf("test done\n");
	free(img->pixels);
	free(img);
	return 0;
}
